package com.fcscs.cservice.client.main.iguestusers;

import java.text.DateFormat;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.extjs.gxt.ui.client.data.BasePagingLoadResult;
import com.extjs.gxt.ui.client.event.BaseEvent;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.store.ListStore;
import com.extjs.gxt.ui.client.widget.HorizontalPanel;
import com.extjs.gxt.ui.client.widget.Label;
import com.extjs.gxt.ui.client.widget.LayoutContainer;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.VerticalPanel;
import com.extjs.gxt.ui.client.widget.form.ComboBox.TriggerAction;
import com.extjs.gxt.ui.client.widget.form.FormPanel;
import com.extjs.gxt.ui.client.widget.layout.ColumnData;
import com.extjs.gxt.ui.client.widget.layout.ColumnLayout;
import com.fcscs.core.common.MainPaginationSearchModel;
import com.fcscs.core.common.SearchResultsContainer;
import com.fcscs.core.common.authority.UserAuthority;
import com.fcscs.core.domain.IdNameModel;
import com.fcscs.core.domain.Property;
import com.fcscs.core.gwt.common.AsyncCallbackListener;
import com.fcscs.core.gwt.common.CoreConstants;
import com.fcscs.core.gwt.common.FormSubmitListener;
import com.fcscs.core.gwt.common.SearchExecutor;
import com.fcscs.core.gwt.common.SessionContext;
import com.fcscs.core.gwt.common.CoreEnums.SubmitType;
import com.fcscs.core.gwt.common.ui.FcsFields.ClearElementCombobox;
import com.fcscs.core.gwt.common.ui.FcsFields.EasyClearCombobox;
import com.fcscs.core.gwt.common.ui.FcsFields.FormButton;
import com.fcscs.core.gwt.common.ui.CenteredInfo;
import com.fcscs.core.gwt.common.ui.FcsFormPanel;
import com.fcscs.core.gwt.common.ui.FcsPanel;
import com.fcscs.core.gwt.common.ui.IEFriendlyDateField;
import com.fcscs.cservice.client.common.CServiceConstants;
import com.fcscs.cservice.client.common.CserviceControllerUtils;
import com.fcscs.cservice.client.common.TextFieldAndIconButtonField;
import com.fcscs.cservice.client.common.TextFieldAndIconButtonField.TextFieldListener;
import com.fcscs.cservice.client.common.controller.CServiceCommonServiceController;
import com.fcscs.cservice.client.common.controller.ReservationServiceController;
import com.fcscs.cservice.client.common.model.configuration.reservation.PropertyIdNameModelData;
import com.fcscs.cservice.client.common.model.iguestusers.iGuestUsersModel;
import com.fcscs.cservice.client.common.model.iguestusers.iGuestUsersModelData;
import com.fcscs.cservice.client.common.model.reservation.ReservationViewModelData;

import com.fcscs.cservice.client.main.iguestusers.iGuestUsersGrid;

import com.fcscs.cservice.client.main.iguestusers.iGuestUsersDialog;
import com.fcscs.cservice.client.main.iguestusers.AdvancedSearchDialog;
import com.fcscs.cservice.domain.IGuestUserView;
import com.fcscs.cservice.domain.Restaurant;
import com.fcscs.cservice.domain.model.ReservationConfView;
import com.fcscs.cservice.domain.model.ReservationView;
import com.fcscs.share.gwt.common.ShareGWTConstants;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Widget;

public class iGuestUsersPanel extends FcsPanel {
	private VerticalPanel vp;
	private FormPanel myFormPanel;
	private EasyClearCombobox<PropertyIdNameModelData> propCombox;
	private ListStore<PropertyIdNameModelData> propList = new ListStore<PropertyIdNameModelData>();
	//private ClearElementCombobox<RestaurantsModelData> restaCombox;
	//private ListStore<RestaurantsModelData> restaList = new ListStore<RestaurantsModelData>();
	private HorizontalPanel hp1;
	private HorizontalPanel hp2;
	private TextFieldAndIconButtonField searchFieldBtn;
	private FormButton advancedSearchButton;
	private AdvancedSearchDialog advancedSearchDialog;
	private boolean isAdvancedSearch;
	private ReservationConfView reservationConf;
	private boolean isClearResvStatus;
	private FormButton addButton;
	private iGuestUsersGrid grid;
	//private iGuestUsersAdvancedDialog inAdvancedDialog;
	// Them vao 19/6/2012
	
	private iGuestUsersDialog dialog;
	private List<IdNameModel<Property>> propGroupIdNames;
	private ListStore<PropertyIdNameModelData> propListStore;
	private Long propId;

	public iGuestUsersPanel(String id) {
		super(id);
		//search();
	}

	@Override
	public void init() {
		vp = new VerticalPanel();
		vp.setSpacing(5);

		///Search
		myFormPanel = new FormPanel();
		myFormPanel.setHeading(CoreConstants.CORE_MESSAGES.operation(
				CServiceConstants.CSERVICE_CONSTANTS.i_GuestUsers(),
				CoreConstants.CORE_CONSTANTS.search()));
		myFormPanel.setSize(958, 50);
		myFormPanel.setFrame(true);
		myFormPanel.setId("iGuestUsersPanel_myFormPanel");
		vp.add(myFormPanel);
		
		hp1 = new HorizontalPanel();
		hp1.setSpacing(5);
		hp1.setId("iGuestUsersPanel_hp1");

		hp2 = new HorizontalPanel();
		hp2.setSpacing(5);
		hp2.setId("iGuestUsersPanel_hp2");

		LayoutContainer container1 = new LayoutContainer();
		container1.setLayout(new ColumnLayout());

		LayoutContainer container2 = new LayoutContainer();
		container2.setLayout(new ColumnLayout());
		Label l = new Label(CoreConstants.CORE_CONSTANTS.search()
				+ CServiceConstants.FIELD_SEP);
		//container2.add(l, new ColumnData(80));

		searchFieldBtn = new TextFieldAndIconButtonField(new TextFieldListener() {
		    @Override
		    public void onTextFieldEnterKeyPressSearch(String value) {
			    if(value == null || value.trim().isEmpty()){
				    newSearch(true);
			    }else{
			    	searchFieldBtn.getTextField().clearInvalid();
				    if (value.trim().length() > 1) {
						newSearch(false);
					}else{
						searchFieldBtn.getTextField().forceInvalid(CServiceConstants.CSERVICE_MESSAGES.atLeastenter(2));
					}
			    }
		    }
		
		    @Override
		    public void onIconButtoSearch(String value) {
			    if(value == null || value.trim().isEmpty()){
				    newSearch(true);
			    }else{
			    	searchFieldBtn.getTextField().clearInvalid();
				    if (value.trim().length() > 1) {
						newSearch(false);
					}else{
						searchFieldBtn.getTextField().forceInvalid(CServiceConstants.CSERVICE_MESSAGES.atLeastenter(2));
					}
			    }
		    }
	    });
        searchFieldBtn.setId("ReservationPanel_searchFieldBtn");
	    searchFieldBtn.getTextField().setWidth(260);
	    searchFieldBtn.getTextField().setEmptyText(
			CoreConstants.CORE_CONSTANTS.lastname() + "," + CoreConstants.CORE_CONSTANTS.firstname()
			+ ShareGWTConstants.SHARE_GWT_CONSTANTS.or()
			+ CServiceConstants.CSERVICE_CONSTANTS.confirmationNO());
	    searchFieldBtn.setIcoButtonTitle(ShareGWTConstants.SHARE_GWT_MESSAGES.searchBy(
			CoreConstants.CORE_CONSTANTS.lastname() + "," + CoreConstants.CORE_CONSTANTS.firstname()
			+ ShareGWTConstants.SHARE_GWT_CONSTANTS.or()
			+ CServiceConstants.CSERVICE_CONSTANTS.confirmationNO()));
	    //searchFieldBtn.setStyleAttribute("marginLeft", "100px");
	    //searchFieldBtn.setStyleAttribute("marginTop", "10px");
	    searchFieldBtn.getTextField().addListener(Events.OnBlur, new Listener<BaseEvent>(){
			@Override
			public void handleEvent(BaseEvent be) {
				String value = searchFieldBtn.getTextField().getValue();
				if(null != value 
				   && !value.trim().isEmpty()
				   && value.trim().length() < 2){
					searchFieldBtn.getTextField().forceInvalid(CServiceConstants.CSERVICE_MESSAGES.atLeastenter(2));
				}else{
					searchFieldBtn.getTextField().clearInvalid();
				}
			}
	    });
		container2.add(searchFieldBtn, new ColumnData(230));

//Tao AdvanceSearch
		advancedSearchButton = new FormButton(CServiceConstants.CSERVICE_CONSTANTS.advancedSearch());
	    advancedSearchButton.setId("ReservationPanel_advancedSearchButton");
	    advancedSearchButton.setStyleAttribute("marginLeft", "140px");
	    //advancedSearchButton.setStyleAttribute("marginTop", "10px");
	    advancedSearchButton.addSelectionListener(new SelectionListener<ButtonEvent>(){
			@Override
			public void componentSelected(ButtonEvent ce) {
				advancedSearchDialog = AdvancedSearchDialog.getInstance(new FormSubmitListener<ReservationView>(){
					@Override
					public void formSubmitCallBack(
							FcsFormPanel<ReservationView> form,
							SubmitType submitType) {
						newSearch(true);
						advancedSearchDialog.hide();
					}
				}, reservationConf);
				//advancedSearchDialog.getFormPanel().updateForm(new ReservationView());
				advancedSearchDialog.show();
				isClearResvStatus = true;
				searchFieldBtn.getTextField().clear();
				//reservationStatusCombobox.clear();
				isAdvancedSearch = true;
				isClearResvStatus = false;
			}
	    });
	    //myFormPanel.add(advancedSearchButton);
	    container2.add(advancedSearchButton, new ColumnData(120));

		hp2.add(container2);
		myFormPanel.add(hp2);
//dong advanceSearch
		
		propListStore = new ListStore<PropertyIdNameModelData>();
		propCombox = new EasyClearCombobox<PropertyIdNameModelData>();
		propCombox.setId("TitleAdminPanel_propCombox");
//		propCombox.setFieldLabel(CoreConstants.CORE_CONSTANTS.property());
		propCombox.setWidth(200);
		propCombox.setDisplayField(CoreConstants.FULLTNAME);
		propCombox.setAllowBlank(false);
		propCombox.setForceSelection(true);
		propCombox.setTriggerAction(TriggerAction.ALL);
		propCombox.setStore(propListStore);
		
		
		searchFieldBtn = new TextFieldAndIconButtonField(new TextFieldListener() {
			
			@Override
			public void onTextFieldEnterKeyPressSearch(String value) {
				if(value == null || value.trim().isEmpty()){
//					newSearch(true);
					//searchTitle();
				}else{
//					newSearch(false);
					//searchTitle();
				}
			}
			
			@Override
			public void onIconButtoSearch(String value) {
				
				if(value == null || value.trim().isEmpty()){
//					newSearch(true);
					//searchTitle();
				}else{
//					newSearch(false);
					//searchTitle();
				}
			}
		});
		searchFieldBtn.setId("TitleAdminPanel_searchFieldBtn");
		searchFieldBtn.setStyleAttribute(CServiceConstants.CSS_MARGINLEFT, "13px");
		searchFieldBtn.getHicButton().setTitle(ShareGWTConstants.SHARE_GWT_MESSAGES.searchBy(
				CoreConstants.CORE_CONSTANTS.name()+ShareGWTConstants.SHARE_GWT_CONSTANTS.and()+CoreConstants.CORE_CONSTANTS.secondaryName()));
//		hp.add(searchFieldBtn);
		
		//vp.add(hp);

		grid = new iGuestUsersGrid(CServiceConstants.CSERVICE_CONSTANTS.i_GuestUsers(),
				new SearchExecutor<iGuestUsersModelData, MainPaginationSearchModel>() {

					@Override
					public void doSearch(final MainPaginationSearchModel searchModel,
							final AsyncCallback<BasePagingLoadResult<iGuestUsersModelData>> callback) {
//						List<iGuestUsersModelData> iGuestUserList = new ArrayList<iGuestUsersModelData>();
//						iGuestUsersModel model1 = new iGuestUsersModel();
//						model1.setRoom("bi001");
//						model1.setGuestName("guest001");
////						model1.setCategroy("cate001");
////						model1.setDeliveryDate("2012-4-26");
////						model1.setDeliveryTime("15:07");
//						model1.setStatus("pending");
//						iGuestUserList.add(new iGuestUsersModelData(model1));
//
//						iGuestUsersModel model2 = new iGuestUsersModel();
//						model2.setRoom("bi002");
//						model2.setGuestName("guest002");
////						model2.setCategroy("cate002");
////						model2.setDeliveryDate("2012-4-27");
////						model2.setDeliveryTime("18:03");
//						model2.setStatus("completed");
//						iGuestUserList.add(new iGuestUsersModelData(model2));
//						callback.onSuccess(FcsPanel.createPagingLoadResult(
//								iGuestUserList, searchModel.getCurrentPage(),
//								searchModel.getResultsPerPage(), iGuestUserList.size()));
						
						
						

						CServiceCommonServiceController.getINSTANCE().getListIGuestUserView(new AsyncCallbackListener<List<IGuestUserView>>(){

									@Override
									public void onLogin(String username) {
										CServiceCommonServiceController.getINSTANCE().getListIGuestUserView(this);												
									}

									@Override
									public void onFailure(Throwable caught) {
										MessageBox.alert(CoreConstants.CORE_MESSAGES.operation(CoreConstants.CORE_CONSTANTS.system(), ShareGWTConstants.SHARE_GWT_CONSTANTS.error()),
												CoreConstants.CORE_CONSTANTS.systemError(), null);
									}

//									@Override
//									public void onSuccess(
//											SearchResultsContainer<ReservationView> result) {
//										reservationViewModelList = new ArrayList<ReservationViewModelData>();
//										for(ReservationView rv : result.getResults()){
//											reservationViewModelList.add(new ReservationViewModelData(rv));
//										}
//										callback.onSuccess(FcsPanel.createPagingLoadResult(reservationViewModelList,searchModel.getCurrentPage(),
//												searchModel.getResultsPerPage(),result.getTotalCnt()));
//									}

								

									@Override
									public void onSuccess(
											List<IGuestUserView> result) {
										// TODO Auto-generated method stub
										List<iGuestUsersModelData> iGuestUserList = new ArrayList<iGuestUsersModelData>();
										for(IGuestUserView v : result) {
											iGuestUsersModel model = new iGuestUsersModel();
											model.setRoom(v.getRoomNumber());
											model.setGuestName(v.getTitle() + " " + v.getFirstName() + " " + v.getLastName());
//											Format df = new SimpleDateFormat("MM/dd/yyyy");  
//											model.setDepartureDT(df.format(v.getDepartureDateTime()));
											model.setStatus("None");
											iGuestUserList.add(new iGuestUsersModelData(model));
										}
										callback.onSuccess(FcsPanel.createPagingLoadResult(
												iGuestUserList, searchModel.getCurrentPage(),
												searchModel.getResultsPerPage(), iGuestUserList.size()));
									}
							
						});
					
					}
				});

		vp.add(grid);
		add(vp);
		onShow();
	}

	@Override
	public UserAuthority getRequiredAuthority() {
		return null;
	}

	@Override
	protected Widget getViewPanel() {
		return null;
	}

	@Override
	public void onShow() {
		loadPropStore();
		newSearch(true);
	}
	
	protected void newSearch(boolean all) {
		String term = null;
		if (all) {
			term = null;
		}else {
			term = searchFieldBtn.getTextFieldValue().trim();
		}
		MainPaginationSearchModel sm = new MainPaginationSearchModel();
		sm.setSearchTerm(term);
		grid.newSearch(sm);
	}
	
	
	public void loadPropStore() {
		propList.removeAll();
		List<IdNameModel<Property>> listIdNameModel = SessionContext.getInstance().getPropertyGroup();
		IdNameModel<Property> noGroup = new IdNameModel<Property>(SessionContext.getInstance()
				.getPropertyId(), SessionContext.getInstance().getPropertyName());
		if (listIdNameModel.size() == 0) {
			propList.add(new PropertyIdNameModelData(noGroup));
		} else {
			for (IdNameModel<Property> inm : listIdNameModel) {
				propList.add(new PropertyIdNameModelData(inm));
			}
		}
		propCombox.setValue(propList.findModel(CoreConstants.ID, SessionContext.getInstance()
				.getPropertyId()));
	}
	
	@Override
	public boolean onHide() {
		return true;
	}
}
